const https = require('https');
const config = require('../config');
const weixinpay = require('../util/weixinpay');
const url = require('url');
function handle(request, response) {
    let code = request.body.code;
    if (code) {
        //config.wxApi.jscode2session+'?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code'
        https.get(config.wxApi.jscode2session + '?appid=' + config.wxApp.AppId + '&secret=' + config.wxApp.AppSecret + '&js_code=' + code + '&grant_type=authorization_code', (res) => {
            res.on('data', (d) => {
                let json = JSON.parse(d.toString());
                if (json.errcode) {
                    response.end(json.errmsg);
                }
                if (json.session_key && json.openid) {
                    weixinpay.pay(request,response);
                }
                console.log();
            });
        }).on('error', (e) => {
            console.error(e);
        });
    }
}

exports.handle = handle;